<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix"><span>更换头像</span></div>
      <!-- 头像 -->
      <div class="img-box">
        <img
          class="img"
          src="@/assets/images/avatar.jpg"
          alt=""
          v-if="!avatar"
        />
        <img class="img" :src="avatar" alt="" v-else />
      </div>
      <div class="btn-upload">
        <input
          type="file"
          name=""
          id=""
          style="display: none"
          ref="iptRef"
          @change="onFlieChange"
        />
        <el-button type="primary" @click="chooseImg"
          ><i class="el-icon-plus"></i>选择图片</el-button
        >
        <el-button type="success" @click="uploadAvatar"
          ><I class="el-icon-upload">上传头像</I></el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script>
import { updatedUserAvatarApi } from '@/api/index'
export default {
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    // 用按钮的点击事件触发input[type=file]的点击事件
    chooseImg () {
      this.$refs.iptRef.click()
    },
    // 选择图片确定
    onFlieChange (e) {
      const files = e.target.files // 拿到用户选择的文件数组
      if (files.length === 0) {
        // 判断文件数组的长度0没有选择
        this.avatar = ''
      } else {
        // this.avatar = URL.createObjectURL(files[0])
        const fr = new FileReader()
        fr.readAsDataURL(files[0]) // 传入文件对象开始阅读
        fr.onload = (e) => {
          // onlad等待把文件读成base64字符串后会触发onload时间函数
          // e.target.result的值就是读完的结果
          this.avatar = e.target.result
        }
      }
    },
    // 上传头像
    async uploadAvatar () {
      const { data: res } = await updatedUserAvatarApi(this.avatar)
      if (res.code === 0) {
        this.$message.success(res.message)
        // 上传头像并更新vuex
        this.$store.dispatch('getUSerInfo')
      } else {
        return this.$message.error(res.message)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.btn-upload {
  margin-top: 8px;
}
.img-box {
  width: 350px;
  height: 350px;
  border: 1px solid pink;
  .img {
    width: 350px;
    height: 350px;
    object-fit: cover;
  }
}
</style>
